﻿using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Sharp.DataTransferObject;
using Sharp.Infrastructure.WebApiClient;
using Sharp.Portal.Mvc.OAuth.Sharp.Server;
using Sharp.ServiceContracts;

namespace Sharp.Services.OAuth.Controllers
{
    public class GrantController : Controller
    {
        // GET: OAuth/Grant
        public async Task<ActionResult> Index()
        {
            ViewBag.Scope = Request.QueryString["Scope"];
            var clientId = Request.QueryString["client_id"];
            if (clientId == null)
            {
                throw new Exception("client_id不存在.");
            }
            SubSystemDTO sys;
            using (var proxy = new WebApiClientServiceProxy<IPlatformService>())
            {
                sys = await proxy.Channel.GetSubSystemByClientId(clientId);
                if (sys == null)
                {
                    throw new Exception("该client_id不存在应用.");
                }
            }

            ViewBag.AccessUrl = Url.Content("~/") + Setting.EndPointConfig.AuthorizeGrantAccess + Request.Url.Query;
            return View(sys);
        }

        /// <summary>
        /// 授权
        /// </summary>
        /// <returns></returns>
        public ActionResult Access()
        {
            var clientId = Request.QueryString["client_id"];
            var userId = User.Identity.GetUserId();
            //  _ticketStore.Set("TemporaryAuthorization" + clientID + "$" + userID, "", 2);
            return Redirect(Url.Content("~/") + Setting.EndPointConfig.AuthorizeEndpointPath.TrimStart('/') + Request.Url.Query);
        }
    }
}